package com.itheima.reggie.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    //jwt校验
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //取出请求头
        String token = request.getHeader("Authorization");
        //非空判断
        if (StrUtil.isBlank(token)) {
            return loginError(response);
        }
        //处理Bearer 注意：后面包含一个空格
        token = token.replace("Bearer ", "");
        Map map = JwtUtil.parseToken(token);
        //解析失败
        if (map == null) {
            //没携带请求头，拦截，返回
            return loginError(response);
        }
        //查询redis中的user对象
        String phone = (String) map.get("phone");
        User user = (User) redisTemplate.opsForValue().get("phone:" + phone);
        //没找到
        if (user == null) {
            //没携带请求头，拦截，返回
            return loginError(response);
        }
        //登陆成功
        redisTemplate.expire("phone:" + phone, Duration.ofDays(1));
        UserHolder.set(user);
        return true;
    }
    //失败拦截
    private boolean loginError(HttpServletResponse response) throws IOException {
        //没携带请求头，拦截，返回
        ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
        //将其变成josn串
        String json = JSON.toJSONString(resultInfo);
        //响应结果
        response.setContentType("application/json;charset=utf-8"); // MIME类型
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
